import { Component, OnInit, OnDestroy, ViewChild, ElementRef, AfterViewInit, NgZone } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { StockDataService } from '../../shared/services/stock-data.service';
import { ExcelExportService } from '../../shared/services/excel-export.service';
import { Subscription } from 'rxjs';
import * as echarts from 'echarts';
import { NgxEchartsModule } from 'ngx-echarts';

interface AnalysisFilter {
  warehouseName?: string;
  goodsType?: string;
  periodType: 'daily' | 'weekly' | 'monthly';
  dateRange: { start: Date, end: Date };
}

interface AbcAnalysisItem {
  goodsCode: string;
  goodsName: string;
  goodsType: string;
  salesValue: number;
  salesPercent: number;
  cumulativePercent: number;
  abcClass: 'A' | 'B' | 'C';
}

@Component({
  selector: 'app-stock-analysis',
  standalone: true,
  imports: [CommonModule, FormsModule, NgxEchartsModule],
  template: `
    <div class="analysis-container">
      <div class="analysis-header">
        <h2>库存分析报表</h2>
        
        <div class="analysis-actions">
          <div class="filter-section">
            <div class="row">
              <div class="col-md-3">
                <label for="warehouseFilter">仓库</label>
                <select id="warehouseFilter" class="form-select" 
                        [(ngModel)]="filter.warehouseName" (change)="onFilterChange()">
                  <option [ngValue]="undefined">全部仓库</option>
                  <option *ngFor="let warehouse of warehouseOptions" [value]="warehouse">
                    {{warehouse}}
                  </option>
                </select>
              </div>
              
              <div class="col-md-3">
                <label for="goodsTypeFilter">货品类型</label>
                <select id="goodsTypeFilter" class="form-select" 
                        [(ngModel)]="filter.goodsType" (change)="onFilterChange()">
                  <option [ngValue]="undefined">全部类型</option>
                  <option *ngFor="let type of goodsTypeOptions" [value]="type">
                    {{type}}
                  </option>
                </select>
              </div>
              
              <div class="col-md-3">
                <label for="periodTypeFilter">周期类型</label>
                <select id="periodTypeFilter" class="form-select" 
                        [(ngModel)]="filter.periodType" (change)="onFilterChange()">
                  <option value="daily">日</option>
                  <option value="weekly">周</option>
                  <option value="monthly">月</option>
                </select>
              </div>
              
              <div class="col-md-3">
                <label>数据刷新时间</label>
                <div class="update-time">
                  {{lastUpdateTime | date:'yyyy-MM-dd HH:mm:ss'}}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="analysis-content">
        <!-- 库存健康度概览 -->
        <div class="analysis-card stock-health">
          <h3>库存健康度概览</h3>
          <div class="row stats-row">
            <div class="col-md-3">
              <div class="stat-item">
                <div class="stat-value">{{stockHealthStats.healthScore.toFixed(1)}}</div>
                <div class="stat-label">健康指数</div>
                <div class="stat-progress">
                  <div class="progress" style="height: 10px;">
                    <div class="progress-bar" [ngClass]="getHealthScoreClass()"
                         [style.width]="(stockHealthStats.healthScore) + '%'"></div>
                  </div>
                </div>
              </div>
            </div>
            
            <div class="col-md-3">
              <div class="stat-item">
                <div class="stat-value">{{stockHealthStats.turnoverRate.toFixed(2)}}</div>
                <div class="stat-label">周转率</div>
              </div>
            </div>
            
            <div class="col-md-3">
              <div class="stat-item">
                <div class="stat-value">{{stockHealthStats.stockDays}}</div>
                <div class="stat-label">库存天数</div>
              </div>
            </div>
            
            <div class="col-md-3">
              <div class="stat-item">
                <div class="stat-value">{{stockHealthStats.deadStockRatio.toFixed(1)}}%</div>
                <div class="stat-label">呆滞率</div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 库存周转率分析 -->
        <div class="analysis-card stock-turnover">
          <h3>库存周转率分析</h3>
          <div class="chart-container" #turnoverChartContainer style="height: 300px;"></div>
        </div>
        
        <!-- 库存趋势分析 -->
        <div class="analysis-card stock-trend">
          <h3>库存趋势分析</h3>
          <div class="chart-container" #trendChartContainer style="height: 300px;"></div>
        </div>
        
        <!-- ABC分析 -->
        <div class="analysis-card stock-abc">
          <h3>ABC分类分析</h3>
          
          <div class="row">
            <div class="col-md-6">
              <div class="chart-container" #abcChartContainer style="height: 300px;"></div>
            </div>
            
            <div class="col-md-6">
              <table class="table table-striped abc-table">
                <thead>
                  <tr>
                    <th>分类</th>
                    <th>SKU数量</th>
                    <th>SKU占比</th>
                    <th>销售额占比</th>
                    <th>管理策略</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td><span class="badge bg-danger">A 类</span></td>
                    <td>{{abcStats.aCount}}</td>
                    <td>{{abcStats.aSkuPercent.toFixed(1)}}%</td>
                    <td>{{abcStats.aSalesPercent.toFixed(1)}}%</td>
                    <td>严格控制，确保供应</td>
                  </tr>
                  <tr>
                    <td><span class="badge bg-warning">B 类</span></td>
                    <td>{{abcStats.bCount}}</td>
                    <td>{{abcStats.bSkuPercent.toFixed(1)}}%</td>
                    <td>{{abcStats.bSalesPercent.toFixed(1)}}%</td>
                    <td>适当控制，定期检查</td>
                  </tr>
                  <tr>
                    <td><span class="badge bg-secondary">C 类</span></td>
                    <td>{{abcStats.cCount}}</td>
                    <td>{{abcStats.cSkuPercent.toFixed(1)}}%</td>
                    <td>{{abcStats.cSalesPercent.toFixed(1)}}%</td>
                    <td>简化管理，降低成本</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
        
        <!-- ABC详细列表 -->
        <div class="analysis-card abc-details">
          <h3>ABC分类详细列表</h3>
          <div class="table-responsive">
            <table class="table table-striped">
              <thead>
                <tr>
                  <th>货品编码</th>
                  <th>货品名称</th>
                  <th>类型</th>
                  <th>销售额</th>
                  <th>销售占比</th>
                  <th>累计占比</th>
                  <th>ABC分类</th>
                </tr>
              </thead>
              <tbody>
                <tr *ngFor="let item of abcItems">
                  <td>{{item.goodsCode}}</td>
                  <td>{{item.goodsName}}</td>
                  <td>{{item.goodsType}}</td>
                  <td>¥{{item.salesValue.toFixed(2)}}</td>
                  <td>{{item.salesPercent.toFixed(2)}}%</td>
                  <td>{{item.cumulativePercent.toFixed(2)}}%</td>
                  <td>
                    <span class="badge" 
                         [ngClass]="{'bg-danger': item.abcClass === 'A', 
                                    'bg-warning': item.abcClass === 'B', 
                                    'bg-secondary': item.abcClass === 'C'}">
                      {{item.abcClass}} 类
                    </span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  `,
  styles: [`
    .analysis-container {
      padding: 1rem;
    }
    
    .analysis-header {
      margin-bottom: 1.5rem;
    }
    
    .analysis-card {
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
      padding: 1rem;
      margin-bottom: 1.5rem;
    }
    
    .stats-row {
      margin-top: 1.5rem;
    }
    
    .stat-item {
      text-align: center;
      padding: 0.5rem;
    }
    
    .stat-value {
      font-size: 1.8rem;
      font-weight: bold;
      margin-bottom: 0.3rem;
    }
    
    .stat-label {
      color: #666;
      font-size: 0.9rem;
    }
    
    .stat-progress {
      margin-top: 0.5rem;
    }
    
    h3 {
      font-size: 1.2rem;
      margin-bottom: 1rem;
      padding-bottom: 0.5rem;
      border-bottom: 1px solid #eee;
    }
    
    .update-time {
      padding: 0.5rem;
      border: 1px solid #eee;
      border-radius: 4px;
      background-color: #f9f9f9;
    }
    
    .filter-section {
      margin-bottom: 1rem;
    }
    
    .abc-table {
      font-size: 0.9rem;
    }
  `]
})
export class StockAnalysisComponent implements OnInit, OnDestroy, AfterViewInit {
  // 过滤条件
  filter: AnalysisFilter = {
    periodType: 'monthly',
    dateRange: {
      start: new Date(new Date().setMonth(new Date().getMonth() - 6)),
      end: new Date()
    }
  };

  // 选项数据
  warehouseOptions: string[] = [];
  goodsTypeOptions: string[] = [];
  
  // 统计数据
  stockHealthStats = {
    healthScore: 75.5,
    turnoverRate: 3.2,
    stockDays: 28,
    deadStockRatio: 5.8
  };
  
  // ABC分析数据
  abcItems: AbcAnalysisItem[] = [];
  abcStats = {
    aCount: 0,
    bCount: 0,
    cCount: 0,
    aSkuPercent: 0,
    bSkuPercent: 0,
    cSkuPercent: 0,
    aSalesPercent: 0,
    bSalesPercent: 0,
    cSalesPercent: 0
  };
  
  // 最后更新时间
  lastUpdateTime: Date = new Date();
  
  // 图表实例
  private turnoverChart: echarts.ECharts | null = null;
  private trendChart: echarts.ECharts | null = null;
  private abcChart: echarts.ECharts | null = null;
  
  // 数据订阅
  private subscription = new Subscription();

  @ViewChild('turnoverChartContainer') turnoverChartContainer!: ElementRef;
  @ViewChild('trendChartContainer') trendChartContainer!: ElementRef;
  @ViewChild('abcChartContainer') abcChartContainer!: ElementRef;

  constructor(
    private http: HttpClient,
    private stockDataService: StockDataService,
    private excelExportService: ExcelExportService,
    private ngZone: NgZone
  ) {}

  ngOnInit(): void {
    // 订阅更新时间
    this.subscription.add(
      this.stockDataService.lastUpdateTime$.subscribe(time => {
        this.lastUpdateTime = time;
      })
    );
    
    // 加载选项数据
    this.loadOptions();
    
    // 加载分析数据
    this.loadAnalysisData();
  }

  ngAfterViewInit(): void {
    // 初始化图表
    this.ngZone.runOutsideAngular(() => {
      setTimeout(() => {
        this.initCharts();
        this.updateCharts();
      }, 300);
    });
    
    // 添加窗口大小变化监听，以便调整图表大小
    window.addEventListener('resize', this.resizeCharts.bind(this));
  }
  
  /**
   * 初始化图表
   */
  private initCharts(): void {
    // 初始化周转率图表
    if (!this.turnoverChart && this.turnoverChartContainer) {
      this.turnoverChart = echarts.init(this.turnoverChartContainer.nativeElement);
    }
    
    // 初始化趋势图表
    if (!this.trendChart && this.trendChartContainer) {
      this.trendChart = echarts.init(this.trendChartContainer.nativeElement);
    }
    
    // 初始化ABC分析图表
    if (!this.abcChart && this.abcChartContainer) {
      this.abcChart = echarts.init(this.abcChartContainer.nativeElement);
    }
  }
  
  /**
   * 调整图表大小
   */
  private resizeCharts(): void {
    if (this.turnoverChart) {
      this.turnoverChart.resize();
    }
    
    if (this.trendChart) {
      this.trendChart.resize();
    }
    
    if (this.abcChart) {
      this.abcChart.resize();
    }
  }
  
  /**
   * 更新图表
   */
  private updateCharts(): void {
    this.updateTurnoverChart();
    this.updateTrendChart();
    this.updateAbcChart();
  }
  
  /**
   * 更新周转率图表
   */
  private updateTurnoverChart(): void {
    if (!this.turnoverChart) return;
    
    // 模拟不同货品类型的周转率数据
    const categories = ['办公设备', '食品饮料', '电子产品', '办公用品', '家用类'];
    const turnoverRates = [4.2, 6.8, 3.5, 5.1, 2.9];
    const industryAvg = [5.0, 7.5, 4.0, 5.5, 3.2];
    
    const option = {
      title: {
        text: '各类货品周转率对比',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['实际周转率', '行业平均'],
        bottom: '0%'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: categories
      },
      yAxis: {
        type: 'value',
        name: '周转率'
      },
      series: [
        {
          name: '实际周转率',
          type: 'bar',
          data: turnoverRates,
          itemStyle: {
            color: '#5470c6'
          }
        },
        {
          name: '行业平均',
          type: 'line',
          data: industryAvg,
          itemStyle: {
            color: '#ee6666'
          },
          lineStyle: {
            type: 'dashed'
          }
        }
      ]
    };
    
    this.turnoverChart.setOption(option);
  }
  
  /**
   * 更新趋势图表
   */
  private updateTrendChart(): void {
    if (!this.trendChart) return;
    
    // 根据选定的周期类型生成日期标签
    const dateLabels = this.generateDateLabels();
    
    // 模拟库存数据
    const stockData = Array(dateLabels.length).fill(0).map((_, i) => {
      return Math.round(10000 + Math.random() * 2000 - 1000 + i * 100);
    });
    
    // 模拟出入库数据
    const inStockData = Array(dateLabels.length).fill(0).map(() => Math.round(500 + Math.random() * 300));
    const outStockData = Array(dateLabels.length).fill(0).map(() => Math.round(480 + Math.random() * 320));
    
    const option = {
      title: {
        text: '库存趋势分析',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          crossStyle: {
            color: '#999'
          }
        }
      },
      toolbox: {
        feature: {
          dataView: { show: true, readOnly: false },
          magicType: { show: true, type: ['line', 'bar'] },
          restore: { show: true },
          saveAsImage: { show: true }
        }
      },
      legend: {
        data: ['库存量', '入库量', '出库量'],
        bottom: '0%'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          data: dateLabels,
          axisPointer: {
            type: 'shadow'
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          name: '库存量',
          min: Math.min(...stockData) * 0.8,
          axisLabel: {
            formatter: '{value}'
          }
        },
        {
          type: 'value',
          name: '出入库量',
          axisLabel: {
            formatter: '{value}'
          }
        }
      ],
      series: [
        {
          name: '库存量',
          type: 'line',
          data: stockData,
          smooth: true,
          lineStyle: {
            width: 3
          }
        },
        {
          name: '入库量',
          type: 'bar',
          yAxisIndex: 1,
          data: inStockData,
          itemStyle: {
            color: '#91cc75'
          }
        },
        {
          name: '出库量',
          type: 'bar',
          yAxisIndex: 1,
          data: outStockData,
          itemStyle: {
            color: '#ee6666'
          }
        }
      ]
    };
    
    this.trendChart.setOption(option);
  }
  
  /**
   * 更新ABC分析图表
   */
  private updateAbcChart(): void {
    if (!this.abcChart) return;
    
    // 从ABC分析数据计算帕累托图数据
    const salesPercent = this.abcItems.map(item => item.salesPercent);
    const cumulativePercent = this.abcItems.map(item => item.cumulativePercent);
    
    // 简化的x轴标签
    const xLabels = Array(this.abcItems.length).fill(0).map((_, i) => {
      if (i % Math.max(1, Math.floor(this.abcItems.length / 10)) === 0) {
        return (i + 1).toString();
      }
      return '';
    });
    
    const option = {
      title: {
        text: '帕累托分析图',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        },
        formatter: function(params: any) {
          const dataIndex = params[0].dataIndex;
          if (dataIndex >= 0 && dataIndex < this.abcItems.length) {
            const item = this.abcItems[dataIndex];
            return `
              ${item.goodsName}<br/>
              销售额: ¥${item.salesValue.toFixed(2)}<br/>
              销售占比: ${item.salesPercent.toFixed(2)}%<br/>
              累计占比: ${item.cumulativePercent.toFixed(2)}%<br/>
              ABC分类: ${item.abcClass}类
            `;
          }
          return '';
        }.bind(this)
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: xLabels,
        name: 'SKU排序'
      },
      yAxis: [
        {
          type: 'value',
          name: '销售占比(%)',
          axisLabel: {
            formatter: '{value}%'
          }
        },
        {
          type: 'value',
          name: '累计占比(%)',
          axisLabel: {
            formatter: '{value}%'
          },
          max: 100
        }
      ],
      series: [
        {
          name: '销售占比',
          type: 'bar',
          data: salesPercent,
          itemStyle: {
            color: function(params: any) {
              const dataIndex = params.dataIndex;
              if (dataIndex >= 0 && dataIndex < this.abcItems.length) {
                const abcClass = this.abcItems[dataIndex].abcClass;
                if (abcClass === 'A') return '#dc3545';
                if (abcClass === 'B') return '#ffc107';
                return '#6c757d';
              }
              return '#5470c6';
            }.bind(this)
          }
        },
        {
          name: '累计占比',
          type: 'line',
          yAxisIndex: 1,
          data: cumulativePercent,
          smooth: true,
          symbol: 'none',
          lineStyle: {
            width: 3,
            color: '#ee6666'
          },
          markLine: {
            silent: true,
            lineStyle: {
              color: '#333'
            },
            data: [
              {
                yAxis: 80,
                label: {
                  formatter: 'A类 (80%)',
                  position: 'start'
                }
              },
              {
                yAxis: 95,
                label: {
                  formatter: 'B类 (95%)',
                  position: 'start'
                }
              }
            ]
          }
        }
      ]
    };
    
    this.abcChart.setOption(option);
  }
  
  /**
   * 根据过滤条件生成日期标签
   */
  private generateDateLabels(): string[] {
    const { periodType, dateRange } = this.filter;
    const labels: string[] = [];
    const startDate = new Date(dateRange.start);
    const endDate = new Date(dateRange.end);
    
    switch (periodType) {
      case 'daily':
        // 每日数据，最多显示30天
        for (let d = new Date(startDate); d <= endDate && labels.length < 30; d.setDate(d.getDate() + 1)) {
          labels.push(d.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' }));
        }
        break;
      
      case 'weekly':
        // 每周数据，最多显示26周
        for (let d = new Date(startDate); d <= endDate && labels.length < 26; d.setDate(d.getDate() + 7)) {
          const weekNumber = Math.ceil((d.getDate() + new Date(d.getFullYear(), d.getMonth(), 1).getDay()) / 7);
          labels.push(`${d.getMonth() + 1}月第${weekNumber}周`);
        }
        break;
      
      case 'monthly':
        // 每月数据，最多显示24个月
        for (let d = new Date(startDate); d <= endDate && labels.length < 24; d.setMonth(d.getMonth() + 1)) {
          labels.push(`${d.getFullYear()}-${d.getMonth() + 1}月`);
        }
        break;
    }
    
    return labels;
  }
  
  /**
   * 加载选项数据
   */
  private loadOptions(): void {
    // 从库存数据服务获取仓库和类型选项
    this.subscription.add(
      this.stockDataService.stockByWarehouse$.subscribe(data => {
        this.warehouseOptions = data.map(item => item.warehouseName);
      })
    );
    
    this.subscription.add(
      this.stockDataService.stockByType$.subscribe(data => {
        this.goodsTypeOptions = data.map(item => item.goodsType);
      })
    );
  }
  
  /**
   * 加载分析数据
   */
  private loadAnalysisData(): void {
    // 加载库存健康度数据（实际项目中应从API获取）
    // 这里使用模拟数据
    this.stockHealthStats = {
      healthScore: 75.5 + Math.random() * 10 - 5,
      turnoverRate: 3.2 + Math.random() * 0.6 - 0.3,
      stockDays: 28 + Math.floor(Math.random() * 6 - 3),
      deadStockRatio: 5.8 + Math.random() * 2 - 1
    };
    
    // 生成ABC分析数据
    this.generateAbcData();
  }
  
  /**
   * 生成ABC分析数据
   */
  private generateAbcData(): void {
    // 模拟商品销售数据
    const sampleGoods = [
      { code: 'G001', name: '高端笔记本电脑', type: '电子产品', sales: 250000 },
      { code: 'G002', name: '智能手机', type: '电子产品', sales: 180000 },
      { code: 'G003', name: '打印机', type: '办公设备', sales: 120000 },
      { code: 'G004', name: '办公桌', type: '办公设备', sales: 95000 },
      { code: 'G005', name: '办公椅', type: '办公设备', sales: 85000 },
      { code: 'G006', name: '投影仪', type: '电子产品', sales: 78000 },
      { code: 'G007', name: '饮水机', type: '办公设备', sales: 65000 },
      { code: 'G008', name: '复印纸', type: '办公用品', sales: 58000 },
      { code: 'G009', name: '签字笔', type: '办公用品', sales: 45000 },
      { code: 'G010', name: '文件夹', type: '办公用品', sales: 38000 },
      { code: 'G011', name: '订书机', type: '办公用品', sales: 35000 },
      { code: 'G012', name: '笔记本', type: '办公用品', sales: 32000 },
      { code: 'G013', name: '咖啡机', type: '食品饮料', sales: 30000 },
      { code: 'G014', name: '矿泉水', type: '食品饮料', sales: 28000 },
      { code: 'G015', name: '咖啡豆', type: '食品饮料', sales: 25000 },
      { code: 'G016', name: '茶叶', type: '食品饮料', sales: 23000 },
      { code: 'G017', name: '饼干', type: '食品饮料', sales: 22000 },
      { code: 'G018', name: '巧克力', type: '食品饮料', sales: 20000 },
      { code: 'G019', name: '鼠标垫', type: '办公用品', sales: 15000 },
      { code: 'G020', name: '计算器', type: '办公用品', sales: 12000 },
      { code: 'G021', name: '回形针', type: '办公用品', sales: 10000 },
      { code: 'G022', name: '橡皮擦', type: '办公用品', sales: 8000 },
      { code: 'G023', name: '便利贴', type: '办公用品', sales: 7000 },
      { code: 'G024', name: '尺子', type: '办公用品', sales: 5000 },
      { code: 'G025', name: '胶水', type: '办公用品', sales: 4000 }
    ];
    
    // 应用过滤器
    let filteredGoods = [...sampleGoods];
    
    if (this.filter.goodsType) {
      filteredGoods = filteredGoods.filter(item => item.type === this.filter.goodsType);
    }
    
    // 计算总销售额
    const totalSales = filteredGoods.reduce((sum, item) => sum + item.sales, 0);
    
    // 按销售额降序排序
    filteredGoods.sort((a, b) => b.sales - a.sales);
    
    // 计算销售占比和累计占比
    let cumulativePercent = 0;
    
    this.abcItems = filteredGoods.map(item => {
      const salesPercent = (item.sales / totalSales) * 100;
      cumulativePercent += salesPercent;
      
      // 根据累计占比确定ABC分类
      let abcClass: 'A' | 'B' | 'C' = 'C';
      if (cumulativePercent <= 80) {
        abcClass = 'A';
      } else if (cumulativePercent <= 95) {
        abcClass = 'B';
      }
      
      return {
        goodsCode: item.code,
        goodsName: item.name,
        goodsType: item.type,
        salesValue: item.sales,
        salesPercent,
        cumulativePercent,
        abcClass
      };
    });
    
    // 计算ABC分类统计数据
    const aItems = this.abcItems.filter(item => item.abcClass === 'A');
    const bItems = this.abcItems.filter(item => item.abcClass === 'B');
    const cItems = this.abcItems.filter(item => item.abcClass === 'C');
    
    const totalItems = this.abcItems.length;
    const aSalesPercent = aItems.reduce((sum, item) => sum + item.salesPercent, 0);
    const bSalesPercent = bItems.reduce((sum, item) => sum + item.salesPercent, 0);
    const cSalesPercent = cItems.reduce((sum, item) => sum + item.salesPercent, 0);
    
    this.abcStats = {
      aCount: aItems.length,
      bCount: bItems.length,
      cCount: cItems.length,
      aSkuPercent: (aItems.length / totalItems) * 100,
      bSkuPercent: (bItems.length / totalItems) * 100,
      cSkuPercent: (cItems.length / totalItems) * 100,
      aSalesPercent,
      bSalesPercent,
      cSalesPercent
    };
    
    // 更新图表
    if (this.abcChart) {
      this.updateAbcChart();
    }
  }
  
  /**
   * 过滤条件变更事件
   */
  onFilterChange(): void {
    // 重新加载分析数据
    this.loadAnalysisData();
    
    // 更新图表
    this.updateCharts();
  }
  
  /**
   * 获取健康分数对应的CSS类
   */
  getHealthScoreClass(): string {
    const score = this.stockHealthStats.healthScore;
    
    if (score >= 80) {
      return 'bg-success';
    } else if (score >= 60) {
      return 'bg-info';
    } else if (score >= 40) {
      return 'bg-warning';
    } else {
      return 'bg-danger';
    }
  }
  
  ngOnDestroy(): void {
    // 取消订阅
    this.subscription.unsubscribe();
    
    // 移除窗口大小变化监听
    window.removeEventListener('resize', this.resizeCharts.bind(this));
    
    // 销毁图表实例
    if (this.turnoverChart) {
      this.turnoverChart.dispose();
      this.turnoverChart = null;
    }
    
    if (this.trendChart) {
      this.trendChart.dispose();
      this.trendChart = null;
    }
    
    if (this.abcChart) {
      this.abcChart.dispose();
      this.abcChart = null;
    }
  }
} 